﻿#region Copyright and Licensing Notice
// Copyright (C) 2011 Steven Bosnick
// 
// This program is open source software; you can redistribute it 
// and/or modifiy it under the terms of the Eclipse Public License,
// version 1.0.
// 
// This program is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied
// warranty of MERCHANTABILITY or FITNESS FOR A 
// PARTICULAR PURPOSE. See the Eclipse Public License for more
// details.
// 
// You should have received a copy of the Eclipse Public License 
// along with this program; if not, you can find a copy at
// "http://www.opensource.org/licenses/eclipse-1.0.php".
#endregion
using System;
using System.Threading.Tasks;
using BitwiseOre.Properties;
using BitwiseOre.SharedMemory.Core.Common;

namespace BitwiseOre.SharedMemory.Core
{
    internal sealed class Writer : IWriter
    {
        private static readonly string AttemptedFlushOfEmptyBufferMessage = Resources.Writer_AttemptedFlushOfEmptyBufferMessage;

        private readonly IConnectionQueues _connectionQueues;
        private readonly Func<TimeSpan, ITimeoutHelper> _createTimeoutHelper;

        public Writer(IConnectionQueues connectionQueues, Func<TimeSpan, ITimeoutHelper> createTimeoutHelper)
        {
            _connectionQueues = connectionQueues;
            _createTimeoutHelper = createTimeoutHelper;
        }

        public void Flush()
        {
            if (_connectionQueues.IsCurrentWriteBufferEmpty)
            {
                throw new InvalidOperationException(AttemptedFlushOfEmptyBufferMessage);
            }
            _connectionQueues.FlushWriteBuffer();
        }

        public Task Write(ArraySegment<byte> array, TimeSpan timeOut)
        {
            var helper = _createTimeoutHelper(timeOut);

            return new Task(
                () =>
                    {
                        if (_connectionQueues.IsCurrentWriteBuffer)
                        {
                            _connectionQueues.WriteToCurrentBuffer(array, helper);
                        }
                        else
                        {
                            _connectionQueues.WriteToNextBuffer(array, helper);
                        }
                    });
        }

        public void WriteByte(byte value, TimeSpan timeOut)
        {
            var success = _connectionQueues.IsCurrentWriteBuffer &&
                          _connectionQueues.WriteByteToCurrentBuffer(value);

            if (success) return;

            var write = Write(new ArraySegment<byte>(new[] {value}), timeOut);
            write.RunSynchronously();
            if (write.Exception != null)
            {
                throw write.Exception;
            }
        }
    }
}